import moment from 'moment'

Component({
  options: {
    addGlobalClass: true,
  },

  properties: {
    id: {
      type: String,
      value: '',
      observer(id) {
        if (this.properties.thresholds?.length) {
          this.createIntersectionObserverHandle();
        }
      },
    },
    data: {
      type: Object,
      observer(data) {
        if (!data) {
          return;
        }
        if (data.carImages != null && data.carImages != "") {
          var imgs = data.carImages.split(',');
          for (var i = 0; i < imgs.length; i++) {
            imgs[i] = getApp().globalData.imageUrl + imgs[i];
          }
          data.carImages = imgs;
          data.image = data.carImages[0];
        }
        this.setData({ goods: data });
      },
    },
    currency: {
      type: String,
      value: '¥',
    },

    thresholds: {
      type: Array,
      value: [],
      observer(thresholds) {
        if (thresholds && thresholds.length) {
          this.createIntersectionObserverHandle();
        } else {
          this.clearIntersectionObserverHandle();
        }
      },
    },
  },

  data: {
    goods: { id: '' },
    visible: false
  },

  lifetimes: {
    ready() {
      this.init();
    },
    detached() {
      this.clear();
    },
  },

  pageLifeTimes: {
    show: function () {
      const $ele1 = this.selectComponent('#loading-img');
      const $ele2 = this.selectComponent('#loading-img-custom');

      this.setLoadingStatus($ele1);
      this.setLoadingStatus($ele2);
    },
  },

  methods: {
    setLoadingStatus(ele) {
      ele.onLoadError = null;
      ele.onLoaded = null;
      ele.setData({
        isLoading: true,
        isFailed: false,
      });
    },
    clickHandle() {
      this.triggerEvent('click', { goods: this.data.goods });
    },
    clickEditHandle() {
      this.triggerEvent('editClick', { goods: this.data.goods });
    },
    onImageViewer() {
      if (this.data.goods.carImages != null && this.data.goods.carImages.length > 0) {
        this.setData({ visible: true })
      }
    },
    onClose(e) {
      this.setData({
        visible: false,
      });
    },

    init() {
      const { thresholds, id } = this.properties;
      if (thresholds && thresholds.length) {
        this.createIntersectionObserverHandle();
      }
    },

    clear() {
      this.clearIntersectionObserverHandle();
    },

    intersectionObserverContext: null,


    clearIntersectionObserverHandle() {
      if (this.intersectionObserverContext) {
        try {
          this.intersectionObserverContext.disconnect();
        } catch (e) { }
        this.intersectionObserverContext = null;
      }
    },
  },
});
